package cn.jbolt.core.enjoy.directive;

import cn.jbolt.core.kit.JBoltUserKit;
import cn.jbolt.core.permission.JBoltUserAuthKit;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;

/**
 * 界面上的权限控制功能 用来控制界面上的菜单、按钮等等元素的显示
 * #permission(PermissionKey.DASHBOARD)
 * <a href="/admin/jboltversion/edit/1">审核</a>
 * #end
 */
public class PermissionDirective extends Directive {

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		Long adminuserId = JBoltUserKit.getUserId();
		if (adminuserId != null) {
			boolean success = JBoltUserAuthKit.hasPermission(adminuserId, true, getPermission(scope));
			if (success) {
				stat.exec(env, scope, writer);
			}
		}
	}

	/**
	 * 从 #permission 指令参数中获取 permission
	 */
	private String getPermission(Scope scope) {
		Object value = exprList.eval(scope);
		if (value instanceof String) {
			return (String) value;
		} else {
			throw new IllegalArgumentException("权限参数只能为 String 类型");
		}
	}
	@Override
	public boolean hasEnd() {
		return true;
	}
}
